package com.sunnyweather.android.ui.weather

import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.sunnyweather.android.R
import com.sunnyweather.android.databinding.*
import com.sunnyweather.android.logic.model.Location
import com.sunnyweather.android.logic.model.Place
import com.sunnyweather.android.logic.model.SkyTransformer
import com.sunnyweather.android.logic.model.Weather
import com.sunnyweather.android.logic.service.AMapPositionService
import com.sunnyweather.android.logic.service.RefreshWeatherService
import com.sunnyweather.android.logic.util.LogUtil
import java.text.SimpleDateFormat
import java.util.*

class WeatherActivity : AppCompatActivity() {


    val weatherViewModel:WeatherViewModel by lazy { ViewModelProvider(this).get(WeatherViewModel::class.java) }

    lateinit var weatherLayoutBinding: WeatherLayoutBinding


    //向外部暴露出当前正在运行的Activity的实例,这里主要是给广播使用，当广播接收到消息时调用这个实例来更新Activity
    //的UI
    companion object{
         var runningInstance:WeatherActivity?=null
        var broadcastManager:LocalBroadcastManager?=null
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //将状态栏设置为透明
        /*val decorView=window.decorView
        decorView.systemUiVisibility=
            View.SYSTEM_UI_FLAG_FULLSCREEN or
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        window.statusBarColor= Color.TRANSPARENT*/

        weatherLayoutBinding= WeatherLayoutBinding.inflate(layoutInflater)

        //获取子视图viewBinding实例
        //viewBinding 碰上引入布局会有bug，直接在这里使用引入布局的viewBinding对象是无法修改布局内容的，以下代码是错误的
        //正确的方式要么在主布局中给引入的布局命名，要么使用bind函数传入主布局的root（前提是子布局被<merge></merge>标签包裹）
        //这里使用第一种方式来解决
         /*nowWeatherBinding=NowWeatherBinding.inflate(layoutInflater)
         forecastWeatherBinding=ForecastWeatherBinding.inflate(layoutInflater)
         lifeIndexBinding=LifeIndexBinding.inflate(layoutInflater)*/

        setContentView(weatherLayoutBinding.root)

        //启动后台刷新服务
        startRefreshWeatherService()

        //注册广播监听
        broadcastManager=LocalBroadcastManager.getInstance(this)
        broadcastManager?.registerReceiver(WeatherReceiver(), IntentFilter("com.sunnyweather.android.UPDATE_WEATHER_UI"))

        //先判断是否有初始数据，没有的话就从intent获取
        if(weatherViewModel.lat==0.0){
            weatherViewModel.lat=intent.getDoubleExtra("place_lat",0.0)
            LogUtil.d("WeatherActivity","${weatherViewModel.lat}")
        }
        if(weatherViewModel.lng==0.0){
            weatherViewModel.lng=intent.getDoubleExtra("place_lng",0.0)
            LogUtil.d("WeatherActivity","${weatherViewModel.lng}")
        }
        if(weatherViewModel.placeName==""){
            weatherViewModel.placeName=intent.getStringExtra("place_name")?:""
            LogUtil.d("WeatherActivity","${weatherViewModel.placeName}")
        }
        LogUtil.d("WeatherViewModel Instance:",weatherViewModel.toString())

        //加载地点选项
        weatherViewModel.getPlaceOptions()

        weatherLayoutBinding.weatherRefresh.setColorSchemeResources(com.google.android.material.R.color.design_default_color_primary)

        //设置LiveData监视器
        weatherViewModel.weatherLiveData.observe(this){result->
            LogUtil.d("LiveDataTest","startObserve result:${result.getOrNull().toString()}")
            if(result.isSuccess){
                val weather=result.getOrNull()
                if(weather!=null){
                    LogUtil.d("WeatherActivity observe","$weather")
                    //Toast.makeText(this,"刷新成功",Toast.LENGTH_SHORT).show()
                    showWeather(weather)
                }else{
                    Toast.makeText(this,"没有查询到天气数据",Toast.LENGTH_SHORT).show()
                    //打印错误
                    result.exceptionOrNull()?.printStackTrace()
                }
                weatherLayoutBinding.weatherRefresh.isRefreshing=false
            }else{
                Toast.makeText(this,"请求失败！请检查网络连接",Toast.LENGTH_SHORT).show()
                weatherLayoutBinding.weatherRefresh.isRefreshing=false
            }
        }

        //设置定位数据监听器
        /*weatherViewModel.setLocalPlaceObserver(this){place->
            LogUtil.d("AmapLocation","refresh UI Data")
            //当定位地点发生改变时，刷新地点列表
            weatherViewModel.getPlaceOptions()
            //如果当前展示的页面正好是localPlace页面，就立刻刷新天气数据
            weatherViewModel.refreshWeather()
            if(weatherLayoutBinding.placeNavigator.selectedItemId==R.id.localPlace){

            }
        }*/

        //打开侧边菜单
        weatherLayoutBinding.nowWeatherLayout.searchPlaceBtn.setOnClickListener {
            weatherLayoutBinding.drawerLayout.openDrawer(GravityCompat.START)
        }

        weatherLayoutBinding.drawerLayout.addDrawerListener(object :DrawerLayout.DrawerListener{
            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
            }

            override fun onDrawerOpened(drawerView: View) {
            }

            override fun onDrawerStateChanged(newState: Int) {
            }

            //当侧边菜单关闭时关闭输入法
            override fun onDrawerClosed(drawerView: View) {
                val manager=getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                manager.hideSoftInputFromWindow(drawerView.windowToken,InputMethodManager.HIDE_NOT_ALWAYS)
            }
        })

        //手动刷新当前天气的操作
        weatherLayoutBinding.weatherRefresh.setOnRefreshListener {
            weatherViewModel.refreshWeather()
            weatherLayoutBinding.weatherRefresh.isRefreshing=true
        }

        //设置导航栏点击事件
        weatherLayoutBinding.placeNavigator.setOnItemSelectedListener {item->
            when(item.itemId){
                R.id.localPlace->{
                        val place=weatherViewModel.placeOptions[0]
                        if(place.name==weatherViewModel.placeName){
                            true
                        }else{
                            weatherViewModel.changePlace(place)
                            weatherViewModel.getWeather()
                            weatherLayoutBinding.deleteBtn.visibility=View.GONE
                            //切换时自定滚动到顶部
                            weatherLayoutBinding.weatherLayout.scrollTo(0,0)
                            true
                        }
                }
                R.id.place1->{
                        if(weatherViewModel.placeOptions.size>1){
                            val place=weatherViewModel.placeOptions[1]
                            if(place.name==weatherViewModel.placeName){
                                true
                            }else{
                                weatherViewModel.changePlace(place)
                                weatherViewModel.getWeather()
                                weatherLayoutBinding.deleteBtn.visibility=View.VISIBLE
                                //切换时自定滚动到顶部
                                weatherLayoutBinding.weatherLayout.scrollTo(0,0)
                                true
                            }
                        }else{
                            false
                        }
                }
                R.id.place2->{
                        if(weatherViewModel.placeOptions.size>2){
                            val place=weatherViewModel.placeOptions[2]
                            if(place.name==weatherViewModel.placeName){
                                true
                            }else{
                                weatherViewModel.changePlace(place)
                                weatherViewModel.getWeather()
                                weatherLayoutBinding.deleteBtn.visibility=View.VISIBLE
                                //切换时自定滚动到顶部
                                weatherLayoutBinding.weatherLayout.scrollTo(0,0)
                                true
                            }
                        }else{
                            false
                        }
                }
                R.id.place3->{
                    if(weatherViewModel.placeOptions.size>3){
                        val place=weatherViewModel.placeOptions[3]
                        if(place.name==weatherViewModel.placeName){
                            true
                        }else{
                            weatherViewModel.changePlace(place)
                            weatherViewModel.getWeather()
                            weatherLayoutBinding.deleteBtn.visibility=View.VISIBLE
                            //切换时自定滚动到顶部
                            weatherLayoutBinding.weatherLayout.scrollTo(0,0)
                            true
                        }
                    }else{
                        false
                    }
                }else->false
            }
        }


        //设置悬浮按钮的点击事件,实现删除常用位置的功能
        weatherLayoutBinding.deleteBtn.setOnClickListener {
            when(weatherLayoutBinding.placeNavigator.selectedItemId){
                R.id.place1->{
                    weatherViewModel.removePlace("0")
                    weatherViewModel.removeWeather(weatherViewModel.lat,weatherViewModel.lng)
                    weatherLayoutBinding.placeNavigator.selectedItemId=R.id.localPlace
                }
                R.id.place2->{
                    weatherViewModel.removePlace("1")
                    weatherViewModel.removeWeather(weatherViewModel.lat,weatherViewModel.lng)
                    weatherLayoutBinding.placeNavigator.selectedItemId=R.id.localPlace
                }
                R.id.place3->{
                    weatherViewModel.removePlace("2")
                    weatherViewModel.removeWeather(weatherViewModel.lat,weatherViewModel.lng)
                    weatherLayoutBinding.placeNavigator.selectedItemId=R.id.localPlace
                }
            }
        }

        //手动请求天气数据
        weatherViewModel.refreshWeather()




        runningInstance=this
    }


    //向视图中填充数据的函数
    fun showWeather(weather: Weather){
        //获取实时天气和天气预报
        val nowWeather=weather.realTime
        val dailyWeather=weather.daily

        //设置天气背景
        weatherLayoutBinding.weatherLayout.setBackgroundResource(SkyTransformer.getSky(nowWeather?.skycon?:"").bg)
        //填充now_weather的数据
        weatherLayoutBinding.nowWeatherLayout.placeName.text=weatherViewModel.placeName
        weatherLayoutBinding.nowWeatherLayout.currentSky.text=SkyTransformer.getSky(nowWeather?.skycon?:"").info
        weatherLayoutBinding.nowWeatherLayout.currentTemp.text=nowWeather?.temperature?.toInt().toString()
        weatherLayoutBinding.nowWeatherLayout.currentAQI.text=nowWeather?.airQuality?.aqi?.chn?.toInt().toString()

        //填充life_index数据
        weatherLayoutBinding.lifeIndexLayout.carWashingText.text=
            dailyWeather?.lifeIndex?.carWashing?.get(0)?.desc
        weatherLayoutBinding.lifeIndexLayout.coldRiskText.text=
            dailyWeather?.lifeIndex?.coldRisk?.get(0)?.desc
        weatherLayoutBinding.lifeIndexLayout.ultravioletText.text=
            dailyWeather?.lifeIndex?.ultraviolet?.get(0)?.desc
        weatherLayoutBinding.lifeIndexLayout.dressingText.text=
            dailyWeather?.lifeIndex?.dressing?.get(0)?.desc

        //填充天气预报的数据
        val daySize= dailyWeather?.skycon?.size
        val dailySkycon=dailyWeather?.skycon
        val dailyTemperature=dailyWeather?.temperature
        val forecastView=weatherLayoutBinding.forecastLayout.forecastLayout
        forecastView.removeAllViews()
        for(i in 0 until daySize!!){
            val view=LayoutInflater.from(this).inflate(R.layout.forecast_item,weatherLayoutBinding.forecastLayout.root,false)
            val forecastItemBinding=ForecastItemBinding.bind(view)
            val date= dailySkycon?.get(i)?.date
            //val dateInfo="${date.year+1900}年${date.month+1}月${date.day}日"
            val dateInfo=SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(date)
            forecastItemBinding.dateInfo.text=dateInfo
            forecastItemBinding.skyIcon.setImageResource(SkyTransformer.getSky(dailySkycon?.get(i)?.value
                ?: "").icon)
            forecastItemBinding.skyInfo.text=SkyTransformer.getSky(dailySkycon?.get(i)?.value ?: "").info
            forecastItemBinding.tempInfo.text="${dailyTemperature?.get(i)?.max?.toInt()}到${dailyTemperature?.get(i)?.min?.toInt()}摄氏度"
            forecastView.addView(forecastItemBinding.root)
        }



        weatherLayoutBinding.weatherLayout.visibility= View.VISIBLE
    }


    private fun startRefreshWeatherService(){
        val intent= Intent(this,RefreshWeatherService::class.java)
        startService(intent)
    }

    override fun onDestroy() {
        AMapPositionService.stop()
        AMapPositionService.destroyClient()
        runningInstance=null
        broadcastManager?.unregisterReceiver(WeatherReceiver())
        broadcastManager=null
        super.onDestroy()
    }
}